package com.app.gridview;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zndroid.gridview.AGridDragAdapter;
import com.zndroid.gridview.GridDroppableLayout;
import com.zndroid.gridview.IImageBean;
import com.zndroid.gridview.inner.drag.GridDragFixedFirstAdapter;
import com.zndroid.gridview.inner.drag.IModeType;
import com.zndroid.gridview.inner.drag.OnItemCapturedListener;
import com.zndroid.gridview.inner.drag.OnItemFixedClickListener;
import com.zndroid.gridview.inner.drag.OnItemTriggerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 固定头部
 * 使用 {@link com.zndroid.gridview.inner.drag.GridDragFixedFirstAdapter}
 * */
public class SendMsgActivity extends AppCompatActivity {
    private GridDroppableLayout layout;
    private GridDragFixedFirstAdapter<ImageInfo> adapter;

    private List<ImageInfo> arrayList = new ArrayList<>();


    TextView textView;

    private int REQUEST_CODE_CHOOSE = 777;
    private int MAX = 9;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_msg);

        initStatusBar();

        layout = findViewById(R.id.gdl);
        textView = findViewById(R.id.view);

        initData();
    }

    private void initData() {
        ImageInfo end = new ImageInfo();
        end.setResId(R.drawable.ic_fixed);
        end.setName("我是固定桩");

        layout.setImageLoader(new GlideImageDisplay());//第一步，指定图片展示引擎

        adapter = new GridDragFixedFirstAdapter<ImageInfo>(this, arrayList, layout.getImageLoader());
        adapter.setFixedPile(end);
        adapter.showDeleteIcon(true);
        adapter.setAutoDismissFixPile(false);//自动过滤固定桩（默认;true）
        adapter.setDataChangedCallBack(new AGridDragAdapter.IDataChangedCallBack() {
            @Override
            public void onChanged(List<? extends IImageBean> allList, List<? extends IImageBean> realityList) {

            }
        });

        layout.setDragAdapter(adapter);
        layout.setMax(MAX);
        layout.setMode(IModeType.LONG_PRESS);
//        layout.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                if (!layout.isTouchMode()&&!layout.isNoneMode() && !adapter.isFixed(position)) {//long press enter edit mode.
//                    layout.setMode(GridDroppableLayout.MODE.TOUCH);
//                    return true;
//                }
//                return false;
//            }
//        });

        layout.setOnItemFixedClickListener(new OnItemFixedClickListener() {
            @Override
            public void onFixedItemClicked(boolean autoDismissFixPile, int position, IImageBean bean, List<? extends IImageBean> realityList) {
                int max = autoDismissFixPile ? (MAX - realityList.size() + 1) : (MAX - realityList.size());
                if (max > 0) {
                    Matisse.from(SendMsgActivity.this)
                            .choose(MimeType.ofAll())
                            .countable(true)
                            .maxSelectable(max)
                            .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                            .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .showPreview(true) // Default is `true`
                            .forResult(REQUEST_CODE_CHOOSE);
                }

                Toast.makeText(SendMsgActivity.this, "固定桩被点击：" + position, Toast.LENGTH_SHORT).show();
            }
        });

        layout.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(SendMsgActivity.this, "click item at " + position, Toast.LENGTH_SHORT).show();
            }
        });
        layout.setOnItemCapturedListener(new OnItemCapturedListener() {
            @Override
            public void onItemCaptured(View v, int position) {
                v.setScaleX(1.1f);
                v.setScaleY(1.1f);
                v.setAlpha(0.9f);
            }

            @Override
            public void onItemReleased(View v, int position) {
                v.setScaleX(1f);
                v.setScaleY(1f);
                v.setAlpha(1f);
            }

        });
//        layout.setOnItemTrackListener(new OnItemTrackListener() {
//            @Override
//            public void onRawTrajectory(float rawX, float rawY) {
//
//            }
//
//            @Override
//            public void onTrajectory(float x, float y) {
//
//            }
//        });

        layout.setTriggerView(textView, new OnItemTriggerListener() {
            @Override
            public void onItemHoldUp(View draggedView, int position) {
                textView.setVisibility(View.VISIBLE);
                textView.setText("拖动到此处删除");
            }

            @Override
            public void onItemHoldReleased(View draggedView, int position) {
                textView.setVisibility(View.GONE);
            }

            @Override
            public void onDragInReleased(View draggedView, int position) {
                arrayList.remove(position);
                adapter.notifyDataSetChanged();
                Toast.makeText(SendMsgActivity.this, "进行删除操作", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDragIn(View draggedView, int position) {
                textView.setText("进去了");
            }

            @Override
            public void onDragOut(View draggedView, int position) {
                textView.setText("出去了");
            }
        });
    }

    public void toSend(View view) {
        for (ImageInfo info : adapter.getFinalResult()) {
            Log.i("hyhy", info.toString());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            for (String s : Matisse.obtainPathResult(data)) {
                ImageInfo info = new ImageInfo();
                info.setFilePath(s);

                arrayList.add(info);
            }

            adapter.notifyDataSetChanged();
        }
    }

    public void initStatusBar() {
        //Android全屏返回布局抖动问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            // 获取状态栏高度
            int statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            View rectView = new View(this);
            // 绘制一个和状态栏一样高的矩形，并添加到视图中
            LinearLayout.LayoutParams params
                    = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
            rectView.setLayoutParams(params);
            //设置状态栏颜色（该颜色根据你的App主题自行更改）
            rectView.setBackgroundColor(ContextCompat.getColor(this, R.color.purple_700));
            // 添加矩形View到布局中
            ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
            decorView.addView(rectView);
            ViewGroup rootView = (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
            rootView.setFitsSystemWindows(true);
            rootView.setClipToPadding(true);
        }
    }
}